package cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "cookie06", value = "/cookie06")
public class Cookie6 extends HttpServlet {

    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // 获取cookie
        Cookie[] cookies = request.getCookies();
        PrintWriter w = response.getWriter();
        boolean flag = false;
        for (Cookie cookie : cookies) {
            String name = cookie.getName();

            if (name.equals("lastTime")) {
                String value = cookie.getValue();
                w.write("202212390606陈煜，欢迎您回来，您上次访问的时间是：<br>");
                // 转换时间字符串格式yyyy-MM-dd HH:mm:ss
                long lastTime = Long.parseLong(value);
                Date date = new Date(lastTime);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                w.write(simpleDateFormat.format(date));
                flag = true;
            }
        }
        if (!flag) {
            w.write("202212390606陈煜，欢迎您首次访问！");
        }
        Cookie cookie = new Cookie("lastTime", System.currentTimeMillis() + "");
        response.addCookie(cookie);
    }

    protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}